//加载express 
const express = require('express');
//实例路由 
const router = express.Router();
//导入数据模型 
const { order } = require('../model/db')
const { ObjectId } = require('mongodb')

//小程序 获取订单数量 只是数量
router.get('/orderCount', async (req, res) => {
    const { openid, acceptMan, status } = req.query; let data = {};
    //为空，则获取所有订单
    if (openid) {
        //获取我的订单
        data = { openid };
    } else if (acceptMan) {
        //获取我帮助的订单 
        data = { acceptMan };
    } else if (status) {
        //获取状态为待帮助的订单 
        data = { status };
    }
    const count = await order.countDocuments(data)
    res.send({ count })
})
//小程序 获取订单
router.get('/orderList', async (req, res) => {
    const { page, pageSizes, openid, acceptMan, status } = req.query; let data = {};
    //为空，则获取所有订单
    if (openid) {
        //获取我的订单
        data = { openid };
    } else if (acceptMan) {
        //获取我帮助的订单 
        data = { acceptMan };
    } else if (status) {
        //获取状态为待帮助的订单
        data = { status };
    } try {
        const result = await order.find(data).skip(page).limit(pageSizes).sort({ publicTime: -1 });
        res.send(result)
    } catch (err) {
        console.log(err)
        res.send('fail');
    }
})
//统计我完成的订单数量和金额 
router.get('/helpedOrders', async (req, res) => {
    try {
        const { acceptMan, status } = req.query;
        const total = await order.aggregate([{ $match: { acceptMan, status } }, {
            $group: {
                _id: '$acceptMan',
                //按照acceptMan分组
                orderCounts: { $sum: 1 }, earnMoney: { $sum: '$payMoney' }
            }
        }]);
        res.send({ status: 'success', total })
    } catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//小程序 删除我的订单 
// router.get('/delOrder', async (req, res) => {
//     try {
//         const { id } = req.query;
//         console.log(req.query)
//         await order.remove({
//             "_id": id
//         })
//         res.send('success')
//     } catch (error) {
//         console.log(error)
//         res.send('fail')
//     }
// })
//接单、确认订单 管理端订单状态修改
router.post('/updateOrder', async (req, res) => {
    try {
        const { id, status, acceptMan, acceptTime, confirmTime } = req.body;
        let data = {}
        if (acceptTime) {//接单
            data = { acceptMan, acceptTime, status }
        } else if (confirmTime) {//确认订单
            data = { confirmTime, status }
        } else if (status) {
            data = { status }
        }
        await order.findByIdAndUpdate(id, data)
        res.send('success')
    } catch (err) {
        res.send('fail');
        console.log(err);
    }

})
//获取订单详情 
router.get('/orderDetail', async (req, res) => {
    try {
        const mongoose = require('mongoose');
        const result = await order.aggregate([{
            $lookup: {
                from: 'userInfo',
                localField: 'acceptMan',
                foreignField: 'openid',
                as: 'acceptManInfo'
            }
        }, {
            $match: {
                _id: mongoose.Types.ObjectId(req.query.id)
            }
        }])
        res.send({ status: 'success', result });
    } catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//管理后台 获取所有订单 
router.get('/admGetOrders', async (req, res) => {
    try {
        const { currentPage: page, pagesize } = req.query
        //获取数据库中的记录总数 
        const total = await order.countDocuments()
        //分页获取管理员 
        const result = await order.find().skip((page - 1) * pagesize).limit(pagesize).sort({ time: -1 })
        res.send({ status: 'success', total, result })
    } catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//删除订单
router.get('/delOrder', async (req, res) => {
    const { _id } = req.query
    order.findByIdAndRemove(_id).then(result => {
        res.send('success')
    }).catch(err => {
        res.send('fail')
    })
})
//管理后台 数据可视化 统计 
router.get('/orderTotal', async (req, res) => {
    try {
        const result = await order.aggregate([{
            $group: {
                _id: '$orderType', orderCounts: { $sum: 1 }
            }
        }])
        res.send({ status: 'success', result })
    } catch (error) {
        console.log(error)
        res.send({ status: 'fail' })
    }
})
//导出路由 
module.exports = router;